<!--
 * @Author: byron
 * @Date: 2021-09-30 23:17:12
 * @LastEditTime: 2021-10-05 14:29:10
-->
<template>
    <el-dialog :title="title || '提示'" :visible.sync="visible" width="20%">
        <span>{{ text }}</span>
        <span slot="footer" class="dialog-footer">
            <el-button @click="confirmAndClose" class="btn">确认</el-button>
        </span>
    </el-dialog>
</template>

<script type="text/ecmascript-6">
import Vue from "vue"

const Confirm = {
    name: "Confirm",
    props: ['visible', 'text', 'title', 'onConfirm'],
    methods: {
        confirmAndClose() {
            this.onConfirm && this.onConfirm()
            this.visible = false
        },
    },
}


console.log(Confirm);
export default Confirm


// 单例调用
let instanceCache

export const confirm = function (text, title, onConfirm = () => {}) {
    // console.log('Confirm', Confirm);
    const ConfirmCtor = Vue.extend(Confirm)
    // console.log('ConfirmCtor', ConfirmCtor);

    const getInstance = function () {
        if (!instanceCache) {
            instanceCache = new ConfirmCtor({
                propsData: {
                    text,
                    title,
                    onConfirm,
                },
            })
            instanceCache.$mount()
            document.body.appendChild(instanceCache.$el)
        } else {
            instanceCache.text = text
            instanceCache.title = title
            instanceCache.onConfirm = onConfirm
        }

        return instanceCache
    }
    const instance = getInstance()
    // console.log('instance', instance);
    // 确保更新的prop渲染到dom
    // 确保动画效果
    Vue.nextTick(() => {
        instance.visible = true
    })
}

export const confirmObj = {
    install: (Vue) => {
        Vue.prototype.$confirm = confirm
    },
}
</script>

<style lang="scss" scoped>
.btn {
    width: 100%;
    background-color: var(--font-title-color) !important;
    border: 1px solid var(--font-title-color) !important;
    color: #fff;

    &:hover {
        color: #fff;
    }
}
</style>
